<template>
  <div style="position: relative;">
    <el-dialog title='商品审核' v-model="props.auditOpen" append-to-body draggable @close="auditCancel" width="900px">
      <el-form ref="auditFormRef" :model="auditForm" label-width="auto" label-position="left">
        <el-form-item label="商品ID" prop="id">
          {{ auditForm?.id }}
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          {{ auditForm?.name }}
        </el-form-item>
        <el-form-item label="商品价格">
          <el-tooltip placement="top">
            <template #content>
            <el-space spacer=" ">
              {{ auditForm.currencyName }}：{{
                  auditForm.price }} {{ auditForm.symbol
                  }}
                人民币：{{ auditForm.cnyprice }}￥
            </el-space>

            </template>
            <el-space spacer=" ">
              <el-text>{{ auditForm.price }} {{ auditForm.symbol
              }}</el-text>
              <el-text type="info">{{ auditForm.cnyprice }}￥</el-text>
            </el-space>
          </el-tooltip>
        </el-form-item>

        <el-form-item label="商品来源">
          {{ auditForm.collectionSiteName }}
        </el-form-item>
        <el-form-item label="链接地址">
          <el-link :href="auditForm?.originUrl" target="_blank" type="primary">{{ auditForm?.originUrl
          }}</el-link>
        </el-form-item>
        <el-form-item label="商品分类" prop="rawCategories">
          <div style="display: flex; flex-wrap: wrap; gap: 5px" v-if="
            auditForm?.rawCategories && auditForm?.rawCategories.length > 0
          ">
            <el-tag v-for="(category, index) in auditForm.rawCategories" :key="index" type="primary">
              {{ category.name }}
            </el-tag>
          </div>
          <div v-else>无</div>
        </el-form-item>
        <el-form-item label="来源语言">
          {{ auditForm?.languageName }}
        </el-form-item>
        <el-form-item label="商品品牌">
          {{ auditForm?.brandName }}
        </el-form-item>


        <el-form-item label="主图" prop="mainImage">
          <image-preview :src="auditForm?.mainImage" :width="100" :height="100" />
        </el-form-item>
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane label="商品规格" name="first">
            <el-table :data="auditForm.productDraftOptionSkuList" height="300">
              <el-table-column label="商品规格" prop="skuKey" />
              <el-table-column label="售价" prop="price">
                <template #header>
                  {{ `售价（${auditForm?.currencyName}）` }}
                </template>
              </el-table-column>
              <el-table-column label="当前库存" prop="quantity" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="second">
            <template #label>

              <el-text :type="activeName === 'second' ? 'primary' : 'info'"
                v-if="auditForm.attributeLength">商品属性</el-text>
              <el-text type="danger" v-else>商品属性<el-icon>
                  <WarningFilled />
                </el-icon></el-text>

            </template>

            <div class="audit-dialog" v-if="auditForm.attributeLength">
              <el-descriptions :column="1">
                <el-descriptions-item v-for="item in auditForm.productDraftAttributeList" :key="item.id"
                  :label="item.attributeName">{{ item.attributeContent }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <el-text v-else type="warning">暂无数据</el-text>
          </el-tab-pane>
          <el-tab-pane name="third">
            <template #label>
              <el-text :type="activeName === 'third' ? 'primary' : 'info'" v-if="auditForm.ImageLength">商品详情</el-text>
              <el-text type="danger" v-else>商品详情<el-icon>
                  <WarningFilled />
                </el-icon></el-text>
            </template>
            <div class="audit-dialog" v-if="auditForm.ImageLength">
              <image-preview v-for="(image, index) in auditForm.descriptionImageList" :src="image" :key="index"
                :width="500" :height="500" />
            </div>
            <el-text v-else type="warning">暂无数据</el-text>
          </el-tab-pane>
          <el-tab-pane name="description">
            <template #label>
              <el-text :type="activeName === 'description' ? 'primary' : 'info'"
                v-if="auditForm.newDescription">商品描述</el-text>
              <el-text type="danger" v-else>商品描述<el-icon>
                  <WarningFilled />
                </el-icon></el-text>
            </template>

            <div class="mb8" v-if="auditForm.newDescription" v-html="auditForm.newDescription"></div>
            <el-text v-else type="warning">暂无数据</el-text>
          </el-tab-pane>
          <el-tab-pane name="seo">
            <template #label>
              <el-text :type="activeName === 'seo' ? 'primary' : 'info'"
                v-if="auditForm.seoDescription || auditForm.seoDescription || auditForm.seoDescription">SEO</el-text>
              <el-text type="danger" v-else>SEO<el-icon>
                  <WarningFilled />
                </el-icon></el-text>
            </template>
            <el-descriptions :column="1" title=" ">
              <el-descriptions-item>SEO标题：{{
                auditForm.seoTitle || '-'
                }}</el-descriptions-item>
              <el-descriptions-item>SEO标签：{{
                auditForm.seoKeywords || '-'
                }}</el-descriptions-item>
              <el-descriptions-item>SEO描述：{{
                auditForm.seoDescription || '-'
                }}</el-descriptions-item>
              <el-descriptions-item>商品标签：{{
                auditForm.tags || '-'
                }}</el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
        <el-form-item label="审核备注" prop="auditRemark" style="margin: 1% 0;">
          <el-input v-model.trim="auditForm.auditRemark" type="textarea" :rows="6" maxlength="300" show-word-limit
            placeholder="请输入内容" resize="none" />
        </el-form-item>
        <el-form-item v-if="props.showDetails" style="position: sticky;bottom: 0;z-index: 1;">
          <el-space spacer=" ">
            <el-button type="primary" @click="auditsubmitForm('passed')">审核通过</el-button>
            <el-button type="danger" @click="auditsubmitForm('notPassed')">审核不通过</el-button>
            <el-button @click="auditCancel">取 消</el-button>
            <el-dropdown placement="top-start" @command="(command) => handleMining(command)">
              <el-button class="el-dropdown-link">
                重采
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="item in incidentList" :key="item.id" :command="item">
                    <el-text :type="item.type">{{ item.title }}</el-text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-space>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["auditsubmitForm", "auditCancel"]);
const props = defineProps({
  auditOpen: {
    type: Boolean,
    default: false,
  },
  publicItem: {
    type: Object,
    default: {},
  },
  showDetails: {
    type: Boolean,
    default: true,
  },
});

const auditForm = ref({});
const activeName = ref("first");
watch(
  () => props.auditOpen,
  () => {
    if (!props.auditOpen) return;
    activeName.value = 'first'
    extractAndInjectStyles()
    getDetails()

  }
);
// 解析并插入 CSS
const extractAndInjectStyles = (newHtml) => {
  const decodedContent = decodeHtml(newHtml); // 先解码 HTML
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = decodedContent;

  // 提取 <style> 并插入 <head>
  const styles = tempDiv.querySelectorAll("style");
  styles.forEach(style => {
    document.head.appendChild(style); // 插入 <head> 让样式生效
    style.remove(); // 从 HTML 结构中移除 <style>，防止 Vue 过滤
  });
  return tempDiv.innerHTML; // 只保留 HTML 部分
};
const decodeHtml = (html) => {
  const textarea = document.createElement("textarea");
  textarea.innerHTML = html;
  return textarea.value;
};
//   确定
const auditsubmitForm = (e) => {
  let from = {
    auditRemark: "", //备注
    auditStatus: "",
  };
  from.auditRemark = auditForm.value.auditRemark;
  if (e === "passed") {
    from.auditStatus = "passed";
    integration("passed", from);
  } else {
    if (!auditForm.value.auditRemark)
      return proxy.$modal.msgWarning(`请填写不通过备注原因`);
    from.auditStatus = "notPassed";
    integration("notPassed", from);
  }
};
const handleMining = (command) => {
  proxy.$modal
    .confirm(`是否需要重新${command.title}`)
    .then(() => {
      product.recollection.recollectionAdd({
        data: {
          id: props.publicItem.id,
          recollectionType: command.recollectionType
        }
      }).then((res) => {
        if (res.code === 200) {
          proxy.$modal.msgSuccess(res.message);
        }
      })

    })
}
// 取消
const auditCancel = () => {
  emits("auditCancel");
};
const getDetails = () => {
  product.draft
    .productdraftGetbyid({
      pathParams: {
        id: props.publicItem.id,
      },
    })
    .then((res) => {
      auditForm.value = {
        ...res.data,
        attributeLength: res.data.productDraftAttributeList.length,
        ImageLength: res.data.descriptionImageList.length,
        newDescription: extractAndInjectStyles(res.data.description)
      };
      // console.log(auditForm.value, "[[[[[]]]]]");
    })
}
const integration = (e, from) => {
  emits("auditsubmitForm", from);
};
const incidentList = [
  {
    id: 0,
    title: '商品采集',
    recollectionType: 'product'
  }, {
    id: 1,
    title: '分类采集',
    recollectionType: 'category'

  }, {
    id: 2,
    title: '整站采集',
    recollectionType: 'site'

  }
]
</script>
<style lang="scss" scoped>
.audit-dialog {
  height: 380px;
  width: 100%;
  overflow-y: auto;
}
</style>